<?php
namespace V5;
class C_Refund extends \ResourceClass
{
    public $isActive = true;
    public $remark = '申请退货';

    public function post(array $req, array $post, &$result)
    {
        try{
            if (!isset($req['uid'])) {
                return 'require user uid';
            }
            if (!isset($req['userType'])) {
                return 'require user type';
            }
            if (!isset($req['k']) || !isset($req['t'])) {
                return 'data error';
            }
            if (!isset($req['enterpriseId'])) {
                return 'require enterprise enterprise_id';
            }

            if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $req['enterpriseId'], $req['t'] . $post['payload'], $req['k']) == false) {
                return 'data illegal';
            }

            $data = base64_decode($post['payload']);
            @parse_str($data, $data);
            if (!array_key_exists('orderId', $data)) {
                return 'missing return order id';
            }
            if (!array_key_exists('total', $data)) {
                return 'no return quantity';
            }
            if (!array_key_exists('detail', $data)) {
                return 'missing return details';
            }
            $detailProduct = explode(';', $data['detail']);

            $refund_order_cls = new \Cls\RefundOrder\Order();
            $order_handel = new  \Biz\OrderHandler();
            $order_cls = $order_handel->getOrderById($data['orderId']);
            $order_detail_list_as_key = array();
            foreach ($order_cls->getDetailList() as $item) {
                $order_detail_list_as_key[$item->getProductSkuId()] = $item;
            }

            if (!empty($detailProduct)) {
                $refund_detail_list = array();
                for ($i = 0; $i < count($detailProduct); $i++) {
                    $productItem = $detailProduct[$i];
                    if (!empty($productItem)) {
                        $productArr = explode(':', $productItem);
                        if (!empty($productArr)) {
                            $product_sku_id = $productArr[0];
                            $productId = $productArr[1];
                            $productRefundNum = $productArr[2];
                            $productAmount = $productArr[3];
                            // 退单详细信息
                            $refund_order_detail_cls = new \Cls\RefundOrder\Detail();
                            $refund_order_detail_cls->setOrderId($data['orderId'])
                                ->setProductId($productId)
                                ->setProductName($order_detail_list_as_key[$product_sku_id]->getProductName())
                                ->setProductSkuId($product_sku_id)
                                ->setProductSkuAttr($order_detail_list_as_key[$product_sku_id]->getProductSkuAttr())
                                ->setProductSkuCode($order_detail_list_as_key[$product_sku_id]->getCode())
                                ->setOriginSkuAmout($productAmount)
                                ->setRefundSkuAmout($productRefundNum)
                                ->setIndividualPacking($order_detail_list_as_key[$product_sku_id]->getIndividualPacking())
                                ->setSkuPrice($order_detail_list_as_key[$product_sku_id]->getPrice())
                                ->setSkuDiscount($order_detail_list_as_key[$product_sku_id]->getActiveDiscount());
                            $refund_detail_list[] = $refund_order_detail_cls;
                        }
                    }
                }
                $refund_order_cls->create($data['orderId'], $refund_detail_list, $data['total']);
                $refund_order_cls->setRemark($data['remark']);
                $last_insert_id = \Biz\RefundOrderHandler::insert($refund_order_cls);

                if ($last_insert_id) {
                    $refund_img_biz = new \Biz\RefundImgHandler();
                    for ($i = 1; $i < 11; $i++) {
                        $img = 'img' . $i;
                        if (strlen($data[$img]) > 0) {
                            $refund_img_cls = new \Cls\RefundOrder\RefundImg();
                            $refund_img_cls->setRefundId($last_insert_id);
                            $refund_img_cls->setImgUrl($this->subImg($data[$img]));
                            $refund_img_cls->setInsertTime(date('Y-m-d H:i:s',time()));
                            $refund_img_biz->insert($refund_img_cls);
                        }
                    }
                }
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    private function subImg($img)
    {
        require_once ROOT . 'lib/alioss/sdk.class.php';
        require_once ROOT . 'lib/alioss/util/oss_util.class.php';
        $file_name = $this->guid() . '.jpg';
        $oss = new \ALIOSS(OSS_ACCESS_ID, OSS_ACCESS_KEY, OSS_ENDPOINT);
        $bucket = OSS_BUCKET_XQ;

        $img = str_replace('data:image/png;base64,', '', $img);
        $img = str_replace(' ', '+', $img);
        $content = base64_decode($img);

        $options = array(
            'content' => $content,
            'length' => strlen($content),
            \ALIOSS::OSS_HEADERS => array(
                'Content-Type' => 'image/pjpeg')
        );
        $res = $oss->upload_file_by_content($bucket, 'images/' . $file_name, $options);
        //$msg = "上传本地到 /" . $bucket . "/" . $file_name;
        //OSSUtil::print_res($res, $msg);
        if ($res->isOk()) {
            return  'images/' . $file_name;
        }
    }

    private function guid()
    {
        mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = substr($charid, 0, 8) . $hyphen
            . substr($charid, 8, 4) . $hyphen
            . substr($charid, 12, 4) . $hyphen
            . substr($charid, 16, 4) . $hyphen
            . substr($charid, 20, 12);
        return $uuid;
    }
}
